嗨,今天是第五天啦,上一次說明了csv使用,今天來說說JSON (JavaScript Object Notation) 的編碼/解碼吧。
JSON (JavaScript Object Notation), specified by RFC 7159 (which obsoletes RFC 4627) and by ECMA-404, is a lightweight data interchange format inspired by JavaScript object literal syntax (although it is not a strict subset of JavaScript [1] ).
上面為JSON的介紹,總之JSON是一種輕量級的數據交換格式也很好閱讀,就像是Python中的Dictionary一樣。
在開始之前當然要確定環境,安裝json這個套件:
virtualenv:source path/to/your/virtualenv/bin/activate
pip3則將pip改成pip3
pip install json
其實json套件,主要只有兩個函數要用,分別是:
json.dumps : 用來將Python的資料類型編成JSON格式。json.loads : 將JSON物件轉為Python資料類型。範例:
dictionary資料,裡面包含name, height, weight 這三個Key的資料。dumps將這個dic轉成JSON的字串。import json
data = {
'name' : 'plusone''',
'height' : 155,
'weight' : 40
}
jsonStr = json.dumps(data, sort_keys=True, indent=1)
print(jsonStr)
data = json.loads(jsonStr)
print(data)
參數:
sort_keys : 這個應該字面上很好理解了,是否排序Key。indent : 若給非負整數,會幫你格式編排好看依照(填入的)數字等級。可以比較兩者差異:
json_str = json.dumps(data, sort_keys=True, indent=5)
print(json_str)
# {
# "height": 155,
# "name": "plusone",
# "someStr": [
# {
# "a": 123,
# "b": 456
# }
# ]
# }
json_str = json.dumps(data, sort_keys=True, indent=1)
print(json_str)
# {
# "height": 155,
# "name": "plusone",
# "someStr": [
# {
# "a": 123,
# "b": 456
# }
# ]
# }
json編碼對Python而言幾乎沒有改變包含None, bool, int, float, str, list, tuple, dictionary。| JSON | Python |
|---|---|
| object | dict |
| array | list |
| string | str |
| number (int) | int |
| number (real) | float |
| true | True |
| false | False |
| null | None |
true/True、false/False,而None則會轉為Null,例如:data = {
'one':True,
'two':False,
'three':None
}
json_str = json.dumps(data, indent=3)
print(json_str)
# output
# {
# "one": true,
# "three": null,
# "two": false
# }
接著要說明pprint()這個套件。在loads()後print()出來會很難閱讀,這時候可以使用pprint():
from pprint import pprint
data = {
'one':True,
'two':False,
'three':
{
'text':[{'something': '2343488854324'},
{'something': '2343453454354'},
{'something': '1231242343545'},
{'something': '3423423432113'}]
}
}
# output
# {'one': True,
# 'three': {'text': [{'something': '2343488854324'},
# {'something': '2343453454354'},
# {'something': '1231242343545'},
# {'something': '3423423432113'}]},
# 'two': False}
若是用print():
# {'one': True, 'two': False, 'three': {'text': [{'something': '2343488854324'}, {'something': '2343453454354'}, {'something': '1231242343545'}, {'something': '3423423432113'}]}}
好的就是這樣,json就到這裡,今天說明了JSON的編碼解碼操作,也介紹了pprint讓資料顯示更美一點,明天見囉!
json — JSON encoder and decoder — Python 3.7.1rc1 documentation
pprint — Data pretty printer — Python 3.7.1rc1 documentation